<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class Index extends Controller
{
    //登录
    public function login()
    {
        if(request()->isMethod('post')){
            //可以一个一个接收，也可以利用only限制
            // $data = [
            //     'username' => request('username'),
            //     'password' => request('password'),
            // ];
            $data = request()->only(['username','password']);
            $result = (new Admin)->login($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '登录成功',
                    'url' => url('admin/index')
                ];
            } else {
                //登录失败不返回
                $msg = [
                    'code' => 0,
                    'msg' => $result,
                ];
            }
            //laravel只要返回的是数组都会自动变成json tp只有success和error返回才是json           
            return $msg;
        }
        //必须写在post外面，get请求  下面的get任然是一个二维数组，所以只能用first
        //$data = (new Admin)->where(['username'=>1,'password'=>1])->get();
        //dd($data);
        return view('admin.index.login');
    }

    //管理员注册
    public function register ()
    {
        if (request()->isMethod('post')){
            $data = request()->only(['username','password','compass','nickname','email']);
            $result = (new Admin)->register($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '注册成功',
                    'url' => url('admin'),
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg' => $result,
                ];
            }
            return $msg;
        }
        return view('admin.index.register');
    }

    //忘记密码
    public function forget ()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['email']);
            $result = (new Admin)->getCode($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '发送验证码成功'
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg' => $result,
                ];
            }
            return $msg ;
        }
        return view('admin.index.forget');
    }

    //重置密码
    public function reset ()
    {
       $data = request()->only(['email','varify']);
       $result = (new Admin)->reset($data);
       if ($result == 1) {
           $msg = [
               'code' => 1,
               'msg' => '重置密码成功,请去邮箱查看',
               'url' => url('admin')
           ];
       } else {
        $msg = [
            'code' => 0,
            'msg' => '重置密码失败',
        ];
       }
       return $msg;
    }
}
